package com.dji.sample.wayline.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dji.sample.wayline.dao.IFlyerMapper;
import com.dji.sample.wayline.model.entity.Flyer;
import com.dji.sample.wayline.service.IFlyerService;
import com.dji.sdk.common.HttpResultResponse;
import com.dji.sdk.common.Pagination;
import com.dji.sdk.common.PaginationData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * 飞手服务实现类
 * 实现对飞手信息进行增删改查操作的具体逻辑
 *
 * @author sean
 * @version 1.0
 * @date 2024/1/1
 */
@Service
@Transactional
@Slf4j
public class FlyerServiceImpl implements IFlyerService {

    @Autowired
    private IFlyerMapper flyerMapper;

    @Override
    public HttpResultResponse<Flyer> createFlyer(Flyer flyer) {
        try {
            // 检查飞手姓名是否已存在
            if (StringUtils.hasText(flyer.getFlyerName())) {
                Optional<Flyer> existingFlyer = getFlyerByName(flyer.getFlyerName());
                if (existingFlyer.isPresent()) {
                    return HttpResultResponse.error("飞手姓名已存在");
                }
            }

            // 检查手机号是否已存在
            if (StringUtils.hasText(flyer.getPhone())) {
                Optional<Flyer> existingFlyer = getFlyerByPhone(flyer.getPhone());
                if (existingFlyer.isPresent()) {
                    return HttpResultResponse.error("手机号已存在");
                }
            }

            int result = flyerMapper.insert(flyer);
            if (result > 0) {
                return HttpResultResponse.success(flyer);
            } else {
                return HttpResultResponse.error("创建飞手失败");
            }
        } catch (Exception e) {
            log.error("创建飞手失败", e);
            return HttpResultResponse.error("创建飞手失败: " + e.getMessage());
        }
    }

    @Override
    public HttpResultResponse<Boolean> deleteFlyerById(Long id) {
        try {
            if (id == null) {
                return HttpResultResponse.error("飞手ID不能为空");
            }

            int result = flyerMapper.deleteById(id);
            // 如果删除的记录不存在，也应该返回成功（幂等性）
            return HttpResultResponse.success(result >= 0);
        } catch (Exception e) {
            log.error("删除飞手失败", e);
            return HttpResultResponse.error("删除飞手失败: " + e.getMessage());
        }
    }

    @Override
    public HttpResultResponse<String> deleteFlyers(List<Long> ids) {
        try {
            if (ids == null || ids.isEmpty()) {
                return HttpResultResponse.error("飞手ID列表不能为空");
            }

            int result = flyerMapper.deleteBatchIds(ids);
            // 修改返回逻辑：只要删除了至少一条记录就认为成功
            // 如果传入的ID中有不存在的，不应该认为是失败
            if (result > 0) {
                return HttpResultResponse.success("批量删除飞手成功");
            }else {
                return HttpResultResponse.error("批量删除飞手失败");
            }
        } catch (Exception e) {
            log.error("批量删除飞手失败", e);
            return HttpResultResponse.error("批量删除飞手失败: " + e.getMessage());
        }
    }

    @Override
    public HttpResultResponse<Boolean> updateFlyer(Flyer flyer) {
        try {
            if (flyer.getId() == null) {
                return HttpResultResponse.error("飞手ID不能为空");
            }

            // 检查飞手是否存在
            Optional<Flyer> existingFlyer = getFlyerById(flyer.getId());
            if (!existingFlyer.isPresent()) {
                return HttpResultResponse.error("飞手不存在");
            }

            // 检查飞手姓名是否与其他飞手重复
            if (StringUtils.hasText(flyer.getFlyerName())) {
                Optional<Flyer> flyerByName = getFlyerByName(flyer.getFlyerName());
                if (flyerByName.isPresent() && !flyerByName.get().getId().equals(flyer.getId())) {
                    return HttpResultResponse.error("飞手姓名已存在");
                }
            }

            // 检查手机号是否与其他飞手重复
            if (StringUtils.hasText(flyer.getPhone())) {
                Optional<Flyer> flyerByPhone = getFlyerByPhone(flyer.getPhone());
                if (flyerByPhone.isPresent() && !flyerByPhone.get().getId().equals(flyer.getId())) {
                    return HttpResultResponse.error("手机号已存在");
                }
            }

            int result = flyerMapper.updateById(flyer);
            // 更新操作：只要没有异常就认为成功
            return HttpResultResponse.success(result >= 0);
        } catch (Exception e) {
            log.error("更新飞手失败", e);
            return HttpResultResponse.error("更新飞手失败: " + e.getMessage());
        }
    }

    @Override
    public Optional<Flyer> getFlyerById(Long id) {
        if (id == null) {
            return Optional.empty();
        }
        return Optional.ofNullable(flyerMapper.selectById(id));
    }

    @Override
    public Optional<Flyer> getFlyerByName(String flyerName) {
        if (!StringUtils.hasText(flyerName)) {
            return Optional.empty();
        }
        
        Flyer flyer = flyerMapper.selectOne(
                new LambdaQueryWrapper<Flyer>()
                        .eq(Flyer::getFlyerName, flyerName)
        );
        return Optional.ofNullable(flyer);
    }

    @Override
    public Optional<Flyer> getFlyerByPhone(String phone) {
        if (!StringUtils.hasText(phone)) {
            return Optional.empty();
        }
        
        Flyer flyer = flyerMapper.selectOne(
                new LambdaQueryWrapper<Flyer>()
                        .eq(Flyer::getPhone, phone)
        );
        return Optional.ofNullable(flyer);
    }

    @Override
    public PaginationData<Flyer> getFlyers(long page, long pageSize, Integer status, Integer level) {
        LambdaQueryWrapper<Flyer> queryWrapper = new LambdaQueryWrapper<Flyer>()
                .eq(Objects.nonNull(status), Flyer::getStatus, status)
                .eq(Objects.nonNull(level), Flyer::getLevel, level)
                .orderByDesc(Flyer::getId);

        Page<Flyer> pageResult = flyerMapper.selectPage(
                new Page<>(page, pageSize), queryWrapper);

        return new PaginationData<Flyer>()
                .setList(pageResult.getRecords())
                .setPagination(new Pagination()
                        .setPage(pageResult.getCurrent())
                        .setPageSize(pageResult.getSize())
                        .setTotal(pageResult.getTotal()));
    }

    @Override
    public List<Flyer> getAllFlyers() {
        return flyerMapper.selectList(
                new LambdaQueryWrapper<Flyer>()
                        .orderByDesc(Flyer::getId)
        );
    }

    @Override
    public List<Flyer> getFlyersByStatus(Integer status) {
        if (status == null) {
            return getAllFlyers();
        }
        
        return flyerMapper.selectList(
                new LambdaQueryWrapper<Flyer>()
                        .eq(Flyer::getStatus, status)
                        .orderByDesc(Flyer::getId)
        );
    }

    @Override
    public List<Flyer> getFlyersByLevel(Integer level) {
        if (level == null) {
            return getAllFlyers();
        }
        
        return flyerMapper.selectList(
                new LambdaQueryWrapper<Flyer>()
                        .eq(Flyer::getLevel, level)
                        .orderByDesc(Flyer::getId)
        );
    }
}